<?php

namespace App\Http\Controllers;


use Illuminate\Http\Request;

use App\Http\Controllers\UsersController as Users;
use App\Http\Controllers\CheckController;



use App\Agent_login_log;
use App\Agent;
use App\Agent_account_log;
use App\Agent_user_log;
use App\Agent_level;
use App\User;
use App\Product;
use App\Product_type;



use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class AgentController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */

    public function __construct()
    {
        //
    }




    /**
     * 代理用户登录
     * 返回代理用户信息
     */

    public function agentLogin(Request $request)
    {

        $ip = '';
        if (!empty($request->input('ip'))){
            $ip = $request->input('ip');
        }

        //代理记录登陆日志
        $log_login = new Agent_login_log();
        $log_login->password = '';
        $log_login->ip = $ip;
        $log_login->status = 0;       //状态0 失败 1 成功

        if (empty($request->input('agent_account'))){
            $log_login->save();
            $return = array(
                'code' => -1,
                'msg' => "用户名输入有误",
                'data' => array()
            );
            return response()->json($return);
        }

        $agent_account = $request->input('agent_account');

        $log_login->agent_account = $agent_account;



        if (empty($request->input('password'))){
            $log_login->save();
            $return = array(
                'code' => -1,
                'msg' => "密码输入有误",
                'data' => array()
            );
            return response()->json($return);
        }

        $password = $request->input('password');

        $where = array(
            'agent_account'=>$agent_account,
            'password'=>$password
        );


        $agent = Agent::where($where)->first();

        if(empty($agent)){
            $log_login->password = $password;
            $log_login->save();
            $return = array(
                'code' => -1,
                'msg' => '用户名或密码错误',
                'data' => array()
            );
            return response()->json($return);
        }


        //生成token
        $token = md5($ip.$agent->agent_id.time());

        $agent_info = array(
            'agent_id' => $agent->agent_id,
            'agent_name' => $agent->agent_name,             //   代理名
            'agent_account' => $agent->agent_account,       //代理用户名
            'balance' => $agent->balance,         //  余额
            'profit' => $agent->profit,          //收益
            'level' => $agent->level,           //   代理级别
            'created_at' => $agent->created_at,
            'updated_at' => $agent->updated_at
        );



        $return = array(
            'code' => 0,
            'msg' => 'OK',
            'data' => array(
                'token'=>(string)$token,
                'agent' => $agent_info
            )
        );
       $time =  date('Y-m-d H:i:s',time());

        $log_login->agent_id = $agent->agent_id;
        $log_login->status = 1;
        $log_login->token = $token;
        $log_login->password = $password;
        $log_login->agent_account = $agent->agent_account;
        $log_login->created_at =$time;
        $log_login->updated_at =$time;
        $log_login->save();


        return response()->json($return);
    }


    /**
     * 代理用户退出登录
     */



    /**
     *
     * 代理添加用户
     *   开号需要填写用户名、密码、连接数，开号根据当前代理等级扣除当前账户相应的余额，增加其上级账户的收益
     */
    public function addAgentUser(Request $request)
    {
        /**
         *
         * token
         */
        if (empty($request->input('token'))){

            $return = array(
                'code' => -1,
                'msg' => "缺少token",
                'data' => array()
            );
            return response()->json($return);
        }
        $token = $request->input('token');



        //  用户名
        if (empty($request->input('name'))){

            $return = array(
                'code' => -1,
                'msg' => "缺少name",
                'data' => array()
            );
            return response()->json($return);
        }

        $name = $request->input('name');

        $users =  User::where('name',$name)->get()->toArray();

        if(!empty($users))
        {
            $return = array(
                'code' => -1,
                'msg' => "用户名已存在",
                'data' => array()
            );
            return response()->json($return);
        }


        //   密码
        if (empty($request->input('password'))){

            $return = array(
                'code' => -1,
                'msg' => "缺少password",
                'data' => array()
            );
            return response()->json($return);
        }

        $password = $request->input('password');

        //  创建时间
        $time =  date('Y-m-d H:i:s',time());


        //  连接数
        if (empty($request->input('conn_num'))){

            $return = array(
                'code' => -1,
                'msg' => "缺少conn_num",
                'data' => array()
            );
            return response()->json($return);
        }

        $conn_num = $request->input('conn_num');


        // 获取购买的产品
        if (empty($request->input('product_id'))){

            $return = array(
                'code' => -1,
                'msg' => "缺少product_id",
                'data' => array()
            );
            return response()->json($return);
        }
        $product_id = $request->input('product_id');



        // 获取购买的产品套餐数量
        if (empty($request->input('number'))){

            $return = array(
                'code' => -1,
                'msg' => "缺少number",
                'data' => array()
            );
            return response()->json($return);
        }
        $number = $request->input('number');

        $user_id = '';
        $agent_login =  Agent_login_log::where('token',$token)->first();

        $agent_id = $agent_login->agent_id;       //  代理ID

        $agent =  Agent::find($agent_id);


        $agent_level = $agent->level;           // 代理级别
        $balance = $agent->balance;               //  代理余额
        $agent_account = $agent->agent_account;               //  代理名称

        $price = Agent_level::find($agent_level);           //   代理级别优惠价格



        $vip_time = '';         //   会员有效时间
        switch($product_id)
        {
            case 4:
                $agent_price = $price->price_week_basic;$vip_time = time()+7*86400*$number;
                break;
            case 1:
                $agent_price = $price->price_month_basic;$vip_time = time()+30*86400*$number;
                break;
            case 2:
                $agent_price = $price->price_season_basic;$vip_time = time()+90*86400*$number;
                break;
            case 3:
                $agent_price = $price->price_year_basic;$vip_time = time()+365*86400*$number;
                break;
            case 6:
                $agent_price = $price->price_month_advanced;$vip_time = time()+30*86400*$number;
                break;
            case 7:
                $agent_price = $price->price_season_advanced;$vip_time = time()+90*86400*$number;
                break;
            case 8:
                $agent_price = $price->price_year_advanced;$vip_time = time()+365*86400*$number;
                break;
        }



//        开号扣除的金额  = 单价*数量*连接数
        $money = $agent_price * $conn_num *$number;


//        检测余额是否满足购买
        if ($balance < $money){
            $return = array(
                'code' => -1,
                'msg' => "金额不足请充值",
                'data' => array()
            );
            return response()->json($return);
        }


        $vip_time = date('Y-m-d H:i:s',$vip_time);



            //   开始添加用户
            $user_info = array(
                'name'=>$name,
                'password'=>$password,
                'vip'=>1,
                'vip_expired'=>$vip_time,           //   会员失效时间
                'con_max'=>$conn_num,
                'created_at'=>$time,
                'updated_at'=>$time,
                'agent_id'=>$agent_id,
            );

            $user_id = User::insertGetId($user_info);


            if(!$user_id)
            {
                $return = array(
                    'code' => -1,
                    'msg' => "添加用户失败",
                    'data' => array()
                );
                return response()->json($return);
            }




        //   充值记录日志
        $account = array(
            'flag'=>-1,
            'balance_affect'=>$money,
            'balance_initial'=>$balance,
            'balance_change'=>$balance-$money,
            'desc'=>'开号扣款',
            'agent_id'=>$agent_id,
            'operator'=>$agent_account,
            'created_at'=>$time,
            'updated_at'=>$time,
        );

        $agent_account = Agent_account_log::insertGetId($account);

        if(!$agent_account)
        {
            $return = array(
                'code' => -1,
                'msg' => "添加充值记录失败",
                'data' => array()
            );
            return response()->json($return);
        }


        //   扣除开户钱数
        $agent->balance = $agent->balance-$money;
        $agent->save();


        //   代理添加用户日志
        $add_user_log = array(
            'agent_id'=>$agent_id,
            'user_id'=>$user_id,
            'product_id'=>$product_id,
            'number'=>$number,
            'conn_num'=>$conn_num,
            'money'=>$money,
            'created_at'=>$time,
            'updated_at'=>$time,
        );

        $agent_user =  Agent_user_log::insertGetId($add_user_log);

        if(!$agent_user)
        {
            $return = array(
                'code' => -1,
                'msg' => "代理添加用户日志插入失败",
                'data' => array()
            );
            return response()->json($return);
        }

        //  添加成功 返回

        $return = array(
            'code' => 0,
            'msg' => "",
            'data' => array()
        );
        return response()->json($return);



    }



    /**
     * 账户记录：账户余额加减记录（充值、扣款）、收益加减记录（收益增加、提现）
     */




    /**
     *获取消费记录
     */
    public function getConsumptionRecord(Request $request)
    {
        $param = self::getParam($request);

        $count =  Agent_account_log::where('agent_id',$param['agent_id'])->where('flag','-1')->count();


        $data = Agent_account_log::where('agent_id',$param['agent_id'])->where('flag','-1')->offset($param['page_size'] * $param['page_no'])->limit($param['page_size'])->get()->toArray();

       $total = ceil($count / $param['page_size']);



        $return = array(
            'code' => 0,
            'msg' => "",
            'data' => array(
                'count'=>$count,
                'total'=>$total,
                'list'=>$data,
            )
        );
        return response()->json($return);


    }



    /**
     * 账号列表
     */

    public function getAccountNumber(Request $request)
    {
        $page_no = 0;
        $page_size=100;

        /**
         *
         * token
         */
        if (empty($request->input('token'))){

            $return = array(
                'code' => -1,
                'msg' => "缺少token",
                'data' => array()
            );
            return response()->json($return);
        }

        $token = $request->input('token');


        if($request->has('page_no'))
        {
            $page_no = $request->input('page_no');
        }
        if($request->has('page_size'))
        {
            $page_size = $request->input('page_size');
        }

        // 分页

        if($page_size <=0 ) $page_size =  10;


        if($page_no){
            $page_no = $page_no - 1;
            if(is_numeric($page_no)){
                if($page_no<0){
                    $page_no = 0;
                }
            }
        }


        $agent_login =  Agent_login_log::where('token',$token)->first();

        $agent_id = $agent_login->agent_id;       //  代理ID

        if(!$agent_id)
        {
            $return = array(
                'code' => -1,
                'msg' => "token失效",
                'data' => array()
            );
            return response()->json($return);
        }


        $count = User::where('agent_id',$agent_id)->count();

        $data = User::where('agent_id',$agent_id)->offset($page_size * $page_no)->limit($page_size)->get(['name','password','vip','vip_expired','created_at','con_max','id']);

        $total = ceil($count / $page_size);

        $return = array(
            'code' => 0,
            'msg' => "",
            'data' => array(
                'count'=>$count,
                'total'=>$total,
                'list'=>$data,
            )
        );
        return response()->json($return);


    }




    /***
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     * 获取代理详情
     */
    public function userInfo(Request $request)
    {

        $param = self::getParam($request);


       $agent =  Agent::find($param['agent_id']);


       $account= Agent_level::find($agent->level);


        $return = array(
            'code' => 0,
            'msg' => "",
            'data' => array(
                'info'=>$agent,
                'account'=>$account,
            )
        );
        return response()->json($return);


    }



    /***
     *
     * 会员续费
     */


    public function renewVip(Request $request)
    {
        /**
         *
         * token
         */
        if (empty($request->input('token'))){

            $return = array(
                'code' => -1,
                'msg' => "缺少token",
                'data' => array()
            );
            return response()->json($return);
        }
        $token = $request->input('token');


        //   用户ID
        if (empty($request->input('user_id'))){

            $return = array(
                'code' => -1,
                'msg' => "缺少user_id",
                'data' => array()
            );
            return response()->json($return);
        }
        $user_id = $request->input('user_id');

        //  连接数
        if (empty($request->input('conn_num'))){

            $return = array(
                'code' => -1,
                'msg' => "缺少conn_num",
                'data' => array()
            );
            return response()->json($return);
        }

        $conn_num = $request->input('conn_num');


        // 获取购买的产品
        if (empty($request->input('product_id'))){

            $return = array(
                'code' => -1,
                'msg' => "缺少product_id",
                'data' => array()
            );
            return response()->json($return);
        }
        $product_id = $request->input('product_id');



        // 获取购买的产品套餐数量
        if (empty($request->input('number'))){

            $return = array(
                'code' => -1,
                'msg' => "缺少number",
                'data' => array()
            );
            return response()->json($return);
        }
        $number = $request->input('number');



        $agent_login =  Agent_login_log::where('token',$token)->first();

        $agent_id = $agent_login->agent_id;       //  代理ID

        $user = User::find($user_id);
        $name = $user->name;
        $password = $user->password;
        $time =  date('Y-m-d H:i:s',time());


        $agent_login =  Agent_login_log::where('token',$token)->first();

        $agent_id = $agent_login->agent_id;       //  代理ID

        $agent =  Agent::find($agent_id);


        $agent_level = $agent->level;           // 代理级别
        $balance = $agent->balance;               //  代理余额
        $agent_account = $agent->agent_account;               //  代理名称

        $price = Agent_level::find($agent_level);           //   代理级别优惠价格



        $vip_time = '';         //   会员有效时间
        switch($product_id)
        {
            case 4:
                $agent_price = $price->price_week_basic;$vip_time = time()+7*86400*$number;
                break;
            case 1:
                $agent_price = $price->price_month_basic;$vip_time = time()+30*86400*$number;
                break;
            case 2:
                $agent_price = $price->price_season_basic;$vip_time = time()+90*86400*$number;
                break;
            case 3:
                $agent_price = $price->price_year_basic;$vip_time = time()+365*86400*$number;
                break;
            case 6:
                $agent_price = $price->price_month_advanced;$vip_time = time()+30*86400*$number;
                break;
            case 7:
                $agent_price = $price->price_season_advanced;$vip_time = time()+90*86400*$number;
                break;
            case 8:
                $agent_price = $price->price_year_advanced;$vip_time = time()+365*86400*$number;
                break;
        }



//        开号扣除的金额  = 单价*数量*连接数
        $money = $agent_price * $conn_num *$number;


//        检测余额是否满足购买
        if ($balance < $money){
            $return = array(
                'code' => -1,
                'msg' => "金额不足请充值",
                'data' => array()
            );
            return response()->json($return);
        }


        $vip_time = date('Y-m-d H:i:s',$vip_time);

        $users =  User::where('name',$name)->get()->toArray();

        // 判断用户是否存在
        if(empty($users))
        {
            $return = array(
                'code' => -1,
                'msg' => "用户不存在",
                'data' => array()
            );
            return response()->json($return);

        }else{

            //   判断用户是否是会员

            $users = User::find($users[0]['id']);
            $vip = $users->vip;

            if( $vip!= 0)
            {
                $surplus_time  =  strtotime($users->vip_expired);//  当前套餐到期时间

                if ($surplus_time>$time){           //  会员没到期


                    $vip_time  =  strtotime($vip_time);//  当前套餐到期时间
                    $vip_time = $vip_time-time();

                    $vip_time = $vip_time+ $surplus_time;
                    $vip_time = date('Y-m-d H:i:s',$vip_time);

                    $users->vip_expired = $vip_time;

                }else{
                    $users->vip_expired = $vip_time;

                }

                $users->save();
            }

        }





        //   充值记录日志
        $account = array(
            'flag'=>-1,
            'balance_affect'=>$money,
            'balance_initial'=>$balance,
            'balance_change'=>$balance-$money,
            'desc'=>'开号扣款',
            'agent_id'=>$agent_id,
            'operator'=>$agent_account,
            'created_at'=>$time,
            'updated_at'=>$time,
        );

        $agent_account = Agent_account_log::insertGetId($account);

        if(!$agent_account)
        {
            $return = array(
                'code' => -1,
                'msg' => "添加充值记录失败",
                'data' => array()
            );
            return response()->json($return);
        }


        //   扣除开户钱数
        $agent->balance = $agent->balance-$money;
        $agent->save();


        //   代理添加用户日志
        $add_user_log = array(
            'agent_id'=>$agent_id,
            'user_id'=>$user_id,
            'product_id'=>$product_id,
            'number'=>$number,
            'conn_num'=>$conn_num,
            'money'=>$money,
            'created_at'=>$time,
            'updated_at'=>$time,
        );

        $agent_user =  Agent_user_log::insertGetId($add_user_log);

        if(!$agent_user)
        {
            $return = array(
                'code' => -1,
                'msg' => "代理添加用户日志插入失败",
                'data' => array()
            );
            return response()->json($return);
        }



        $return = array(
            'code' => 0,
            'msg' => "",
            'data' => array()
        );
        return response()->json($return);


    }


    public function getUserInfo(Request $request)
    {
        $user_id = $request->input('user_id');

        $users = User::find($user_id);


        if(empty($users))
        {
            $return = array(
                'code' => -1,
                'msg' => "非法的用户ID",
                'data' => array()
            );
            return response()->json($return);
        }

        $return = array(
            'code' => 0,
            'msg' => "",
            'data' => array(
                'info'=>$users
            )
        );
        return response()->json($return);

    }





    static function getParam($request)
    {
        $page_no = 0;
        $page_size=100;

        /**
         *
         * token
         */
        if (empty($request->input('token'))){

            $return = array(
                'code' => -1,
                'msg' => "缺少token",
                'data' => array()
            );
            return response()->json($return);
        }

        $token = $request->input('token');


        if($request->has('page_no'))
        {
            $page_no = $request->input('page_no');
        }
        if($request->has('page_size'))
        {
            $page_size = $request->input('page_size');
        }

        // 分页

        if($page_size <=0 ) $page_size =  10;


        if($page_no){   
            $page_no = $page_no - 1;
            if(is_numeric($page_no)){
                if($page_no<0){
                    $page_no = 0;
                }
            }
        }


        $agent_login =  Agent_login_log::where('token',$token)->first();

        $agent_id = $agent_login->agent_id;       //  代理ID

        if(!$agent_id)
        {
            $return = array(
                'code' => -1,
                'msg' => "token失效",
                'data' => array()
            );
            return response()->json($return);
        }

        $param =array(
            'agent_id'=>$agent_id,
            'page_size'=>$page_size,
            'page_no'=>$page_no,
        );

        return $param;
    }


    public function productList(Request $request)
    {
       $product =  Product::where('id','>','0')->get(['type_id','id','name'])->toArray();

        foreach($product as &$item )
        {
            $type=Product_type::find($item['type_id']);
            $item['type_name'] = $type->type_name;
        }


        $return = array(
            'code' => -0,
            'msg' => "",
            'data' => array(
                'list'=>$product
            )
        );
        return response()->json($return);

    }



























































}